require 'iconv'
class PaperAdminController < ApplicationController
    before_filter :authorize, :except =>[ :login, :list]
    before_filter :configure_charsets
    layout "common_layout"
     
   
  def configure_charsets   
    @headers["Content-Type"]="text/html; charset=utf-8" 
  end  
  
  def list
    @paper_pages, @papers = paginate :papers, :order => 'title DESC', :per_page => 10
  end
  
  def mypapers
    @paper_pages, @papers = paginate  :papers,:conditions => ['user_id = ?', session[:user_id]], :order => 'title DESC', :per_page => 10
  end
  def addcomment
    if request.post?
      newcomment=Comment.new(params[:comment])
      newcomment.user_id=session[:user_id]
      newcomment.modify_time=Time.now
      newcomment.save!
    end
    redirect_to :action =>'show',:id => params[:comment][:paper_id]

  end
  def add_paper
    
    unless request.get?
      begin
      @paper=Paper.new(params[:paper])
      @paper.user_id =session[:user_id]
      orignalfile=upload_file(params[:originalfile]['file']) if params[:originalfile]['file']!=""
      pptfile=upload_file(params[:pptfile]['file']) if params[:pptfile]['file']!=""
      transfile=upload_file(params[:transfile]['file']) if params[:transfile]['file']!=""
      @paper.save_url=orignalfile
      @paper.ppt_url=pptfile
      @paper.translation_url=transfile
      @paper.viewcount=0
      @paper.downcount=0
      @paper.upload_time=Time.now
      if @paper.save!
        @paper.add_paper_keywords
        flash[:notice] = 'Paper was successfully created.'       
        redirect_to :action =>'list'
      end
      rescue 
          delete_file(orignalfile) if !orignalfile.nil?
          delete_file(pptfile) if !pptfile.nil?
          delete_file(transfile) if !transfile.nil?
      end
  end
end  
  
  # the user should be the owner of the paper
  def edit
    @paper = Paper.find(params[:id])
    oldkwords=@paper.keywords
    if @paper.user_id!=session[:user_id]
      @errormsg="You have no authority to edit a paper not belong to you"
      render(:template => "error" )
    end
        
      if request.post?  
       @paper.attributes=(params[:paper])
      if @paper.save
         @paper.edit_paper_keywords(oldkwords)
         flash.now[:notice] = "Change Information Successfully!"
      else
         flash.now[:notice] = "Have not Changed Registration Information !"
      end
     end
  end
  # if the user is the self should not add the viewcount
  # viewcount should not be maliciously added
  def show
    @paper = Paper.find(params[:id],:lock=>true)
    @paper.viewcount+=1
    @paper.save!
  end
  

 #simple search	 
def search
  if params[:query].to_s!=""
    @query = params[:query].to_s
    @total, @searchResults1 = Paper.full_text_search(@query, :page => (params[:page]||1))   
   if @total==0
     redirect_to :action=>'no_result'
   end
  else 
     redirect_to :action=>'no_result'
  end
  @pages = pages_for(@total)
end

#composed search
def complex_search
     @query_str=""
     @query_str+="paper_category_id:"+params[:paper][:paper_category_id].to_s
    if params[:title].to_s!=""
     @query_str+=" AND title:"+params[:title].to_s
    end
    if params[:author].to_s!=""
       @query_str+=" AND (author1:"+params[:author].to_s+" OR author2:"+params[:author].to_s+" OR author3:"+params[:author].to_s+" OR author4:"+params[:author].to_s+" OR author5:"+params[:author].to_s+")"
    end
   if params[:publisher].to_s!=""
     @query_str+=" AND publisher:"+params[:publisher].to_s
   end
   if params[:keyword].to_s!=""
       @query_str+=" AND (keyword1:"+params[:keyword].to_s+" OR keyword2:"+params[:keyword].to_s+" OR keyword3:"+params[:keyword].to_s+" OR keyword4:"+params[:keyword].to_s+" OR keyword5:"+params[:keyword].to_s+" OR keyword6:" +params[:keyword].to_s+")"
   end
   if params[:abstract].to_s!=""
     @query_str+=" AND abstract:"+params[:abstract].to_s
   end
  if params[:summary].to_s!=""
     @query_str+=" AND uploader_summary:"+params[:summary].to_s
   end
   @total, @searchResults2= Paper.full_text_search(@query_str, :page => (params[:page]||1))  
    if @total==0
     redirect_to :action=>'no_result'
    end
    @pages = pages_for(@total)
 end


  def delete    
     paper=Paper.find(params[:id])
     if paper.user_id!=session[:user_id]
      @errormsg="You have no authority to delete a paper not belong to you"
      render(:template => "error" )
     end
     paper.delete_keywords_relation
     delete_file(paper.save_url) if paper.save_url!=""
     delete_file(paper.ppt_url) if paper.ppt_url!=""
     delete_file(paper.translation_url) if paper.translation_url!=""
     paper.destroy
     redirect_to :action => 'list'
  end
  
  def download_file
    if params[:filename]
      send_file "#{RAILS_ROOT}/uploadfile/#{params[:filename]}"
    end
  end
  
  private
  def delete_file(filename)
    
    File.delete("#{RAILS_ROOT}/uploadfile/#{filename}") if File.file?("#{RAILS_ROOT}/uploadfile/#{filename}")
   
  end
  
  def upload_file(file)   
    if !file.original_filename.empty?   
      @filename=get_file_name(file.original_filename)
      File.open("#{RAILS_ROOT}/uploadfile/#{@filename}", "wb") do |f|   
        f.write(file.read)
      end   
      return @filename   
    end   
  end
  
  
  
  def get_file_name(filename)   
    if !filename.nil?   
      Time.now.strftime("%Y_%m_%d_%H_%M_%S") + '_' +Iconv.conv("gbk","utf-8",filename)
    end   
  end   
end
